package com.tqz.rc.server.consistency;

/**
 * <p>构建key的类。
 *
 * @author tianqingzhao
 * @since 2021/8/26 17:38
 */
public class KeyBuilder {

    public static final String NAMESPACE_KEY_CONNECTOR = "##";

    public static final String INSTANCE_LIST_KEY_PREFIX = "com.tqz.rc.naming.iplist.";

    private static final String EPHEMERAL_KEY_PREFIX = "ephemeral.";

    public static final String SERVICE_META_KEY_PREFIX = "com.tqz.rc.naming.domains.meta.";

    public static String buildInstanceListKey(String namespaceId, String serviceName, boolean ephemeral) {
        return ephemeral ? buildEphemeralInstanceListKey(namespaceId, serviceName)
                : buildPersistentInstanceListKey(namespaceId, serviceName);
    }

    private static String buildEphemeralInstanceListKey(String namespaceId, String serviceName) {
        return INSTANCE_LIST_KEY_PREFIX + EPHEMERAL_KEY_PREFIX + namespaceId + NAMESPACE_KEY_CONNECTOR + serviceName;
    }

    private static String buildPersistentInstanceListKey(String namespaceId, String serviceName) {
        return INSTANCE_LIST_KEY_PREFIX + namespaceId + NAMESPACE_KEY_CONNECTOR + serviceName;
    }

    public static boolean matchEphemeralInstanceListKey(String key) {
        return key.startsWith(INSTANCE_LIST_KEY_PREFIX + EPHEMERAL_KEY_PREFIX);
    }

    public static String buildServiceMetaKey(String namespaceId, String serviceName) {
        return SERVICE_META_KEY_PREFIX + namespaceId + NAMESPACE_KEY_CONNECTOR + serviceName;
    }
}
